package com.xcx.eduservice.controller.logindexcontorller;


import com.xcx.commonuntils.returnuntls.ErrorEnum;
import com.xcx.commonuntils.returnuntls.ReturnMessage;

import com.xcx.commonuntils.returnuntls.ReturnMessageUtils;
import com.xcx.eduservice.service.MsmService;
import com.xcx.eduservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "发送短信系统")
@RestController
@RequestMapping("/msm")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
@CrossOrigin//解决跨域问题
public class MsmController {

    final private RedisTemplate<String, String> redisTemplate;
    final private MsmService msmService;


    //发送短信的方法
    @ApiOperation(value = "短信验证接口")
    @GetMapping("send/{phone}")
    public ReturnMessage<Object> sendMsm(@ApiParam(name = "phone", value = "手机号", required = true)
                                         @PathVariable String phone) {


        //1 从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return ReturnMessageUtils.success();
        }
        //2 如果redis获取 不到，进行阿里云发送
        //生成随机值，传递阿里云进行发送
        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        //调用service发送短信的方法
        boolean isSend = msmService.send(param, phone);
        if (isSend) {
            //发送成功，把发送成功验证码放到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(phone, code, 30, TimeUnit.MINUTES);
            return ReturnMessageUtils.success();
        } else {
            return ReturnMessageUtils.errorWithEum(ErrorEnum.E_EDU_DELETE_MSM);
        }
    }
}
